<!-- pages/index/index.vue -->
<template>
	<view class="">
		<view class="home">
			<view class="home-top tn-color-white">
				<view class="home-title font-36 font-weight-400 tn-color-white text-center">花瓣记账</view>
				<view class="d-flex" style="margin-top: 60rpx;">
					<view class="date d-flex a-center flex-1" @click="openCalendar">
						<view class="mr-1">
							<text class="font-24">{{ year }}年</text>
							<view><text class="month font-weight mt-1 mr-1">{{ month }}</text><text class="font-32">月</text></view>
						</view>
						<image style="width: 18rpx;" src="../static/三角形 1@2x.png" mode="widthFix"></image>
					</view>
					<view class="income flex-1">
						<view class="font-24">收入</view>
						<view class="font-32 mt-28">{{ monthStats.inAmount }}</view>
					</view>
					<view class="expense flex-1">
						<view class="font-24">支出</view>
						<view class="font-32 mt-28">{{ monthStats.outAmount }}</view>
					</view>
				</view>
			</view>
			<!--  -->
			<view class="home-container ml-2 mr-2">
				<scroll-view :scroll-top="0" scroll-y style="height: 1070rpx;" @scrolltolower="onScroll" refresher-enabled
					:refresher-triggered="triggered" @refresherrefresh="onRefresh">
					<block v-for="item in accountList">
						<view class="account">
							<view class="account-header d-flex j-sb a-center">
								<view class="account-date font-weight-600 font-30">
									<text class="mr-2">{{ dateFormatter(item.date).date}}</text>
									<text>{{ dateFormatter(item.date).week}}</text>
								</view>
								<view class="account-balance font-24 d-flex">
									<view>支￥{{ item.dateStatistics.outAmount}}</view>
									<view class="ml-5">收￥{{ item.dateStatistics.inAmount}}</view>
								</view>
							</view>
							<view class="account-list">
								<block v-for="iten in item.dateList">
									<view class="account-item d-flex j-sb a-center" @click="accountItemClick(iten,item.date)">
										<view class="account-item-left d-flex a-center">
											<view class="account-icon d-flex j-center a-center">
												<image :src="getImg(iten)" mode=""></image>
											</view>
											<view class="account-title">{{ iten.eventType }}</view>
										</view>
										<view class="account-item-right" :class="iten.inOut === 1 ? 'expense': 'income'">
											<text>{{ iten.inOut === 1 ? '-' : '+'}}</text>{{ iten.amount }}
										</view>
									</view>
								</block>
							</view>
						</view>
					</block>
				</scroll-view>
			</view>
			<view class="w-100" style="height: 20rpx;"></view>
			<gy-popup height="292px" title="请选择年份" :show.sync="showCalendar">
				<gy-datetime-picker :showTime="false" :showMonth="false" :showYear="true" :defaultValue="defaultDate"
					:end="defaultDate" @confirm="confirmDate" @cancel="cancelDate">
				</gy-datetime-picker>
			</gy-popup>
			<gy-popup-mask v-if="showCalendar" @tap="cancelDate" />
		</view>
	</view>
</template>

<script>
	import {
		INCOM_LIST,
		EXPEND_LIST
	} from "@/constant/index.js"
	import {
		getAccountList,
		getAccountByMonth
	} from "@/api/index.js"
	import gyPopupMask from '@/components/gy-popup-mask/gy-popup-mask.vue'
	import gyPopup from '@/components/gy-popup/gy-popup.vue'
	import gyDatetimePicker from '@/components/gy-datetime-picker/gy-datetime-picker.vue'
	export default {
		components: {
			gyDatetimePicker,
			gyPopup,
			gyPopupMask
		},
		data() {
			return {
				triggered: false, // 下拉刷新的触发状态
				tabbarHeight: 96,
				accountList: [],
				showCalendar: false,
				year: '',
				month: '',
				queryParams: {
					pageSize: 5,
					lastDate: null,
					uid: '',
					month: null
				},
				userInfo: {},
				monthParams: {
					uid: null,
					month: null,
				}, // 月统计参数
				monthStats: {}, //月统计数据
				accountLen: null,
				isFirst: true,
				hasMoreData: true,
				incomeList: INCOM_LIST, //收入列表
				expendList: EXPEND_LIST, //支出列表
			}
		},
		mounted() {
			uni.getSystemInfo({
				success: res => {
					if (res.osName == 'ios') {
						this.tabbarHeight = 88
					} else {
						this.tabbarHeight = 96
					}
				}
			})
		},
		methods: {
			openCalendar() {
				this.showCalendar = true
				this.$emit('openCalendar')
			},
			onScroll() {
				console.log('hasMoreData', this.hasMoreData);
				if (this.hasMoreData) {
					this.fetchAccountList()
				}
			},
			// 下拉刷新被触发
			async onRefresh() {
				this.triggered = true;
				this.reset()
				await this.fetchAccountList()
				this.triggered = false; // 关闭刷新状态
			},

			getImg(item) {
				if (item.inOut === 1) { // 支出
					for (let iten of this.expendList) {
						if (iten.text === item.eventType) {
							return iten.activeIcon
						}
					}
				} else { // 收入
					for (let iten of this.incomeList) {
						if (iten.text === item.eventType) {
							return iten.activeIcon
						}
					}
				}
			},
			initDate() {
				const date = new Date()
				this.year = date.getFullYear()
				this.month = date.getMonth() + 1
				// 初始日期为当前日期
				this.queryParams.month = this.year + '-' + this.month
				this.monthParams.month = this.year + '-' + this.month
			},
			// 重置
			reset() {
				this.isFirst = true
				this.accountList = []
				this.queryParams.lastDate = null
				this.hasMoreData = true
			},
			// 筛选日期选择
			confirmDate(result) {
				const resultArr = result.split('-')
				this.year = resultArr[0]
				this.month = resultArr[1]
				// 获取查询日期
				this.queryParams.month = result.slice(0, 7)
				this.monthParams.month = result.slice(0, 7)
				this.reset()
				this.fetchAccountList()
				this.fetchAccountByMonth()
				this.showCalendar = false
				this.$emit('closeCaledar')
			},
			cancelDate() {
				this.showCalendar = false
				this.$emit('closeCaledar')
			},
			accountItemClick(item, date) {
				// 序列化对象
				const serializedItem = encodeURIComponent(JSON.stringify(item));
				uni.navigateTo({
					url: `/pages/index/detail?accountDetails=${serializedItem}&date=${date}`
				})
			},
			// 获取账单列表
			fetchAccountList() {
				if (!this.isFirst) this.queryParams.lastDate = this.accountList.length && this.accountList[this.accountList
					.length - 1].date
				const userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : null
				this.queryParams.uid = userInfo.uid
				if (!this.queryParams.uid) return
				getAccountList(this.queryParams).then((res) => {
					if (res.head.code === "0000") {
						if (res.body && res.body.length > 0) {
							this.accountList.push(...res.body)
							this.isFirst = false
						} else {
							this.hasMoreData = false
						}
					} else {
						uni.showToast({
							title: res.head.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			// 按月统计
			fetchAccountByMonth() {
				const userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : null
				this.monthParams.uid = userInfo.uid
				if (!this.monthParams.uid) return
				getAccountByMonth(this.monthParams).then((res) => {
					console.log('res', res);
					if (res.head.code === "0000") {
						this.monthStats = res.body
					} else {
						uni.showToast({
							title: res.head.msg,
							icon: 'none'
						})
					}

				})
			},
			// 日期格式化
			dateFormatter(date) {
				const parsedDate = new Date(date);
				if (isNaN(parsedDate)) {
					return '日期无效'; // 如果日期无效，返回错误信息
				}
				// 获取月份、日期和星期
				const month = parsedDate.getMonth() + 1; // getMonth() 返回的月份是从0开始的，所以需要加1
				const day = parsedDate.getDate();
				const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const weekDay = weekDays[parsedDate.getDay()];
				// 格式化月份和日期，确保它们是两位数
				const formattedMonth = month.toString().padStart(2, '0');
				const formattedDay = day.toString().padStart(2, '0');
				// 返回格式化的日期字符串
				return {
					date: `${formattedMonth}月${formattedDay}日`,
					week: `${weekDay}`
				};
			}

		},


	}
</script>

<style scoped lang="scss">
	.home {
		position: relative;
		// height: 100%;
		min-height: calc(100vh - 172rpx);
		padding-top: 363rpx;
		background-color: #f1f3f6;

		.home-top {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 343rpx;
			padding-bottom: 24rpx;
			background-color: #E74954;
			z-index: 100000;

			.home-title {
				margin-top: 116rpx;
			}

			.date {
				padding-left: 38rpx;

				.month {
					font-size: 60rpx;
					font-family: AkzidenzGroteskBQ, AkzidenzGroteskBQ;
				}
			}
		}

		.home-container {
			width: 710rpx;
			height: 1070rpx;
			box-sizing: border-box;
			border-radius: 27rpx;
			background-color: #f1f3f6;
			overflow: hidden;
			// background-color: #21AD7A;

			.account {
				width: 100%;
				background-color: #fff;

				.account-header {
					width: 100%;
					height: 95rpx;
					box-sizing: border-box;
					padding: 34rpx 32rpx;
					background: #FAFAFA;
					border-radius: 27rpx;

					.account-date {
						color: #2F374E;
					}

					.account-balance {
						font-weight: 400;
						color: #919AAB;
					}
				}

				.account-list {
					box-sizing: border-box;
					padding: 34rpx 32rpx;
					padding-bottom: 0;

					.account-item {
						padding-bottom: 33rpx;
						// background-color: #fab;

						.account-item-left {
							.account-icon {
								width: 67rpx;
								height: 67rpx;
								border-radius: 50%;
								// background-color: #d9e7fe;
								margin-right: 16rpx;

								image {
									width: 100%;
									height: 100%;
								}
							}

							.account-title {
								font-weight: 600;
								font-size: 27rpx;
								color: #2F374E;
							}
						}

						.account-item-right {
							font-family: PingFangSC, PingFang SC;
							font-weight: 600;
							font-size: 29rpx;
							color: #2F374E;

							&.expense {
								color: #E74954;
							}

							&.income {
								color: #21AD7A;
							}
						}
					}
				}
			}
		}
	}

	::v-deep .tn-picker__content__header--confirm {
		background-color: #e74855 !important;
	}
</style>